package com.fastCms.manager.frame.controller;


import com.fastCms.business.frame.constant.ResultCodeConst;
import com.fastCms.business.frame.response.ApiResponse;
import com.fastCms.business.frame.response.ResponseUtil;
import com.fastCms.business.frame.service.FileUploadManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 文件上传接口
 * @Param
 * @Return
 * @Date 2019/3/28 下午3:53 lsquan
 */
@RestController
@RequestMapping("/file")
@Slf4j
@Api(value = "FileUploadController", tags = "后端-文件上传服务")
public class FileUploadController {

    @Autowired
    private FileUploadManageService fileUploadManageServiceImpl;

    @PostMapping("/uploadFile/{dirCode}")
    @ApiOperation(value = "文件上传通用接口")
    public ApiResponse singleFileUpload(@RequestParam("file") MultipartFile file, @PathVariable String dirCode, HttpServletRequest request, HttpServletResponse response) {
//        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));

        if (file.isEmpty()) {
            return ResponseUtil.fail(ResultCodeConst.FILE.FILE_IS_EMPTY, ResultCodeConst.FILE.FILE_IS_EMPTY_MSG);
        }
        try {
            String path = fileUploadManageServiceImpl.uploadFile(file, dirCode);
            return ResponseUtil.success(path);
        } catch (Exception e) {
            log.error("upload file failed" + e, e.getMessage());
        }
        return ResponseUtil.fail("upload fail");
    }

}

